package com.honour.controller.interfaced;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.util.AliPayUtil;
import com.business.service.interfaced.impl.ProductInService;
import com.honour.service.interfaced.CartInManager;
import com.honour.service.interfaced.CouponInManager;
import com.honour.service.interfaced.OrderManager;
import com.honour.service.interfaced.ProductInManager;
import com.system.controller.base.BaseController;
import com.system.util.AppUtil;
import com.system.util.NetworkUtil;
import com.system.util.PageData;
import com.system.util.Tools;
import com.system.util.ToolsUtil;
import com.wxpay.util.WXPayUtil;

/**
 * 订单的控制层
 * 
 * @author zhanglingbing
 * @date 2018年1月30日
 */
@Controller
@RequestMapping(value = "/appOrder")
public class OrderController extends BaseController {

	@Resource(name = "orderService")
	private OrderManager orderService;

	@Resource(name = "cartInService")
	private CartInManager cartInService;

	@Resource(name = "couponInService")
	private CouponInManager couponInService;

	@Resource(name = "proInService")
	private ProductInManager proInService;

	@Resource(name = "productInService")
	private ProductInService productInService;

	/**
	 * 添加用户收货地址
	 * 
	 * @Author zhanglingbing
	 * @date 2018年1月30日
	 * @return
	 *
	 */
	@RequestMapping(value = "/addAdderss")
	@ResponseBody
	public Object saveAdderss() {
		logBefore(logger, "添加用户收货地址");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		logBefore(logger, pd.toString());
		try {
			if (Tools.checkKey("ADDADDERSS", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("saveAdderss", pd)) { // 检查参数
					// 获取默认状态(判断是否默认,若为默认1,则将其他的默认为1的修改为0)
					String status = (String) pd.get("DEFAULTADR");
					logBefore(logger, (String) pd.get("HONOURUSER_ID"));
					// 通过用户id和默认值查询
					PageData isNotAdr = orderService.selectAdrByUserIdAndStatus(pd);
					if ("1".equals(status) && isNotAdr != null) {// 如果存在已经设置位默认的地址则修改
						// 将之前的默认取消
						orderService.updateStatus(pd);
						logBefore(logger, "添加地址====修改状态成功!!");
					}
					// 生成地址id
					pd.put("ADDRESS_ID", this.getSnowId());
					orderService.saveAdderss(pd);
					String id = (String) pd.get("ADDRESS_ID");
					logBefore(logger, id);
					map.put("ADDRESS_ID", id);
					// 返回01为添加成功并返回
					result = "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);

	}

	/**
	 * 修改地址
	 * 
	 * @Author zhanglingbing
	 * @date 2018年1月31日
	 * @return
	 *
	 */
	@RequestMapping(value = "/updateadr")
	@ResponseBody
	public Object updateAdr() {
		logBefore(logger, "修改地址");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		logBefore(logger, pd.toString());
		try {
			if (Tools.checkKey("UPDATEADR", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("updateAdr", pd)) { // 检查参数
					orderService.updateAdr(pd);
					// 返回01为结算至确认订单也查询成功
					result = "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);

	}

	/**
	 * 根据用户id以及地址id查询地址信息
	 * 
	 * @author zhanglingbing
	 * @date 2018年2月27日
	 * @return
	 */
	@RequestMapping(value = "/adrinfo")
	@ResponseBody
	public Object adrInfo() {
		logBefore(logger, "根据用户id以及地址id查询地址信息");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		logBefore(logger, pd.toString());
		try {
			if (Tools.checkKey("ADRINFO", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("adrInfo", pd)) { // 检查参数
					PageData adrInfo = orderService.getAdrInfo(pd);
					// 返回01为结算至确认订单也查询成功
					map.put("adrInfo", adrInfo);
					result = "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);

	}

	/**
	 * 根据用户id与地址id删除地址
	 * 
	 * @author zhanglingbing
	 * @date 2018年2月5日
	 * @return
	 */
	@RequestMapping(value = "/deladr")
	@ResponseBody
	public Object delAddress() {
		logBefore(logger, "根据用户id与地址id删除地址");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		logBefore(logger, pd.toString());
		try {
			if (Tools.checkKey("DELADDRESS", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("delAddress", pd)) { // 检查参数
					orderService.delAddress(pd);
					// 返回01为结算至确认订单也查询成功
					result = "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);

	}

	/**
	 * 设置地址为默认状态
	 * 
	 * @author zhanglingbing
	 * @date 2018年2月1日
	 * @return
	 */
	@RequestMapping(value = "/adrsta")
	@ResponseBody
	public Object updateAdrStatus() {
		logBefore(logger, "设置地址为默认状态");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		logBefore(logger, pd.toString());
		try {
			if (Tools.checkKey("ADRSTA", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("updateAdrStatus", pd)) { // 检查参数
					// 通过用户id和默认值查询
					PageData isNotAdr = orderService.selectAdrByUserIdAndStatus(pd);
					if (isNotAdr != null) {// 如果存在已经设置位默认的地址则修改
						// 将之前的默认取消
						orderService.updateStatus(pd);
						logBefore(logger, "添加地址====修改状态成功!!");
					}
					pd.put("DEFAULTADR", 1);
					// 将目前的设置为默认
					orderService.updateAdr(pd);
					// 返回01为修改成功
					result = "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);

	}

	/**
	 * 查询地址列表
	 * 
	 * @author zhanglingbing
	 * @date 2018年2月1日
	 * @return
	 */
	@RequestMapping(value = "/adrall")
	@ResponseBody
	public Object adrList() {
		logBefore(logger, "查询地址列表");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		logBefore(logger, pd.toString());
		try {
			if (Tools.checkKey("ADRLIST", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("adrList", pd)) { // 检查参数
					List<PageData> adrList = orderService.selectAdrList(pd);
					if (adrList.size() != 0) {
						map.put("pd", adrList);
					}
					map.put("pd", adrList);
					// 返回01为成功
					result = (0 == adrList.size()) ? "02" : "01";
					// result = "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);

	}

	/**
	 * 确认订单页面(结算功能)
	 * 
	 * @Author zhanglingbing
	 * @date 2018年1月31日
	 * @return
	 *
	 */
	@RequestMapping(value = "/firmOder")
	@ResponseBody
	public Object firmOrder() {
		logBefore(logger, "确认订单页面(结算功能)");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		logBefore(logger, pd.toString());
		try {
			if (Tools.checkKey("FIRMODER", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("firmOrder", pd)) { // 检查参数
					Map<String, Object> map1 = new HashMap<String, Object>();
					// Map<String, Object> map2 = new HashMap<String, Object>();
					Map<String, Object> map3 = new HashMap<>();
					List<PageData> couponLists = new ArrayList<>();

					// 商品列表
					pd.put("CHECKED", "1");

					// 修改购物车勾选状态
					String cartIds = (String) pd.get("CARTIDS");
					String[] cartId = cartIds.split(",");
					//修改购物车勾选状态
					for (String c : cartId) {
						pd.put("CART_ID", c);
						cartInService.update(pd);
					}
					pd.put("CART_ID", "");
					//根据勾选状态和用户id查询购物车列表
					List<PageData> proList = cartInService.selectCartListInfo(pd);

					Set<String> busId = new HashSet<>();
					for (PageData p : proList) {
						String bId = (String) p.get("BUSINESS_ID");
						busId.add(bId);
					}

					// 优惠券和计算商品总价
					for (String b : busId) {
						BigDecimal pMoney = new BigDecimal(0);
						for (PageData pList : proList) {
							// 计算购物车中相同店家商品的总价,将其与代金券最低限额查询可用的优惠券

							String businessId = (String) pList.get("BUSINESS_ID");
							// 优惠券(根据商家id以及可用状态=1查询)
							pd.put("BUSINESS_ID", businessId);
							// List<PageData> couponList =
							// couponInService.getCouponsById(pd);
							// map2.put(businessId, couponList);
							// 计算商品总价
							BigDecimal price = (BigDecimal) pList.get("PRO_PRICE");
							int num = (int) pList.get("QUANTITY");
							BigDecimal totalPrice = price.multiply(new BigDecimal(num));
							logBefore(logger, totalPrice.toString());
							pList.put("TOTAL_PRICE", totalPrice);
							if (businessId.equals(b)) {
								pMoney = pMoney.add(totalPrice);
							}
							// pd.put("TOTAL_PRICE", totalPrice);
						}

						map3.put(b, pMoney);

						logBefore(logger, b);
					}

					for (String b : busId) {
						logBefore(logger, b);
						BigDecimal money = (BigDecimal) map3.get(b);
						int moneys = money.intValue();
						logBefore(logger, money.toString());
						String businessId = b;
						pd.put("BUSINESS_ID", businessId);
						pd.put("COUPON_MININUM", moneys);
						List<PageData> couponList = couponInService.getCouponsById(pd);
						if (couponList.size() != 0) {
							for (PageData c : couponList) {
								couponLists.add(c);

							}
							// map2.put(businessId, couponList);
						}
					}

					map1.put("proList", proList);
					map1.put("coupon", couponLists);

					// 查询默认地址
					PageData adress = orderService.selectAdrByUserIdAndStatus(pd);
					map1.put("adress", adress);
					// 红包

					// 返回01为结算至确认订单也查询成功
					map.put("pd", map1);
					result = "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);

	}
	
	/**
	 * 立即购买接口
	 * @author zhanglingbing
	 * @date 2018年4月14日
	 * @return
	 */
	@RequestMapping(value = "/buynow")
	@ResponseBody
	public Object buyNow() {
		logBefore(logger, "立即购买接口");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		logBefore(logger, pd.toString());
		try {
			if (Tools.checkKey("BUYNOW", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("buyNow", pd)) { // 检查参数
					Map<String, Object> map1 = new HashMap<String, Object>();
//					// Map<String, Object> map2 = new HashMap<String, Object>();
//					Map<String, Object> map3 = new HashMap<>();
					List<PageData> proLists = new ArrayList<>();
					
					//通过规格id查询商品信息
					PageData standardInfo = proInService.selectByStandardId(pd);
					//将查询出来的商品id赋值给pd
					pd.put("PRODUCT_ID", standardInfo.get("PRODUCT_ID"));
					PageData product = proInService.selectProByProId(pd);
					//将查询出来的商家id赋值给pd
					String businessId = (String) product.get("BUSINESS_ID");
					pd.put("BUSINESS_ID", businessId);
					//购物车id
					pd.put("CART_ID", this.getSnowId());
					//立即购买接口添加购物车
					cartInService.buyNowSave(pd);
					map1.put("CART_ID", pd.get("CART_ID"));
					
					//商品信息
					PageData proInfo = proInService.selectProInfoByStanId(pd);
					proInfo.put("QUANTITY", pd.get("QUANTITY"));
					proLists.add(proInfo);
					map1.put("proList", proLists);
					
					//优惠券信息
					pd.put("BUSINESS_ID", proInfo.get("BUSINESS_ID"));
					logBefore(logger, (String)proInfo.get("BUSINESS_ID"));
					pd.put("COUPON_MININUM", pd.get("TOTAL_PRICE"));
					List<PageData> couponList = couponInService.getCouponsById(pd);
//					if (couponList.size() != 0) {
					map1.put("coupon", couponList);
//					}else{
//						map.put("coupon", 0);
//					}
					//地址信息
					PageData adress = orderService.selectAdrByUserIdAndStatus(pd);
					map1.put("adress", adress);
					map.put("pd", map1);
					
					result = (proInfo != null)?"01":"02";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);

	}
	

	/**
	 * 提交订单
	 * 
	 * @author zhanglingbing
	 * @date 2018年2月1日
	 * @return
	 */
	@RequestMapping(value = "/commitorder")
	@ResponseBody
	public Object commitOder() {
		logBefore(logger, "提交订单");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		logBefore(logger, pd.toString());
		try {
			if (Tools.checkKey("COMMITODER", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("commitOder", pd)) { // 检查参数
					
					//1.生成订单
					// 生成订单id
					pd.put("ORDER_ID", this.getSnowId());
					// 调用工具类生成订单号
					String getnum = ToolsUtil.Getnum(pd.getString("HONOURUSER_ID"));
					pd.put("ORDERNUMBER", getnum);
					// 订单下单时间
					pd.put("ORDERTIME", ToolsUtil.getStringDate());
					logBefore(logger, pd.toString());
					// 添加订单
					orderService.save(pd);
					
					
					//2.根据用户id和购物车勾选状态查询购物车列表
					//根据勾选状态和用户id查询购物车列表
					pd.put("CHECKED", 1);
					List<PageData> proList = cartInService.selectCartListInfo(pd);
					//3.生成子订单
					PageData oi = new PageData();
					for (PageData p : proList) {
						oi.put("ORDERITEM_ID", this.getSnowId());
						oi.put("ORDER_ID", pd.get("ORDER_ID"));
						oi.put("STANDARD_ID", p.get("STANDARD_ID"));
						oi.put("PRODUCT_NAME", p.get("PROTITLE"));
						oi.put("PRODUCT_IMAGE", p.get("PROSHOWIMG"));
						oi.put("CURRENT_PRICE", p.get("PRO_PRICE"));
						oi.put("QUANTITY", p.get("QUANTITY"));
						// 获取单价以及数量求总价
						BigDecimal price = (BigDecimal) p.get("PRO_PRICE");
						int num = (int) p.get("QUANTITY");
						BigDecimal totalPrice = price.multiply(new BigDecimal(num));
						oi.put("TOTAL_PRICE", totalPrice);
						oi.put("CREATE_TIME", pd.get("ORDERTIME"));
						oi.put("HONOURUSER_ID", pd.get("HONOURUSER_ID"));
						oi.put("ORDERNUMBER", pd.get("ORDERNUMBER"));
						oi.put("BUSINESS_ID", p.get("BUSINESS_ID"));
						oi.put("IS_DELETE", 0);
						oi.put("ORDERSTATUS", "待付款");
						orderService.addOrderitem(oi);
					}
					
					
					//4.调用支付宝或微信接口生成支付信息
					String orderStr = "";
					pd.put("ORDERTYPE", "50");
					switch (pd.getString("PAYTYPE")) {
					case "支付宝":
						orderStr = AliPayUtil.aliPay(pd);
						map.put("orderStr", orderStr);
						map.put("PAYTYPE", "支付宝");
						break;
					case "微信":
						pd.put("spbillCreateIp", NetworkUtil.getIPAddress(getRequest()));
						SortedMap<String, Object> weixinPrePay = WXPayUtil.weixinPrePay(pd);
						map.put("orderStr", weixinPrePay);
						map.put("PAYTYPE", "微信");
						break;
						
					default:
						break;
					}
					map.put("ORDERNUMBER", pd.get("ORDERNUMBER"));
					// 返回01为添加订单成功
					result = "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);

	}

	/**
	 * 一键支付
	 * 
	 * @author zhanglingbing
	 * @date 2018年2月23日
	 * @return
	 */
	@RequestMapping(value = "/payment")
	@ResponseBody
	public Object oneKeyPayment() {
		logBefore(logger, "一键支付");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		logBefore(logger, pd.toString());
		try {
			if (Tools.checkKey("PAYMENT", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("oneKeyPayment", pd)) { // 检查参数
					
					//调用支付宝或微信接口生成支付信息
					String orderStr = "";
					switch (pd.getString("PAYTYPE")) {
					case "支付宝":
						orderStr = AliPayUtil.aliPay(pd);
						map.put("orderStr", orderStr);
						map.put("PAYTYPE", "支付宝");
						break;
					case "微信":
						PageData wxPd = new PageData();
						wxPd.put("ORDERNUMBER", pd.get("ORDERNUMBER"));
						wxPd.put("ORDERMONEY", pd.get("ORDERMONEY"));
						wxPd.put("PROTITLE", "荣耀黑卡+订单号："+ pd.get("ORDERNUMBER"));
						wxPd.put("spbillCreateIp", NetworkUtil.getIPAddress(getRequest()));
						SortedMap<String, Object> weixinPrePay = WXPayUtil.weixinPrePay(wxPd);
						map.put("orderStr", weixinPrePay);
						map.put("PAYTYPE", "微信");
						break;
						
					default:
						break;
					}
					map.put("ORDERNUMBER", pd.get("ORDERNUMBER"));
					// 返回01为添加订单成功
					result = "01";

				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);

	}
/*	@RequestMapping(value = "/payment")
	@ResponseBody
	public Object oneKeyPayment() {
		logBefore(logger, "一键支付");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		logBefore(logger, pd.toString());
		try {
			if (Tools.checkKey("PAYMENT", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("oneKeyPayment", pd)) { // 检查参数
					// 商品id集合
					Set<String> proIdList = new HashSet<>();
					Map<String, Integer> proNumber = new HashMap<>();
					
					// 调用支付接口,支付成功则将PAYSTATUS赋值为1,支付失败赋值为0
					
					// 获取paytype支付状态,判断状态!=1则未支付,将物流,支付方式置为空,订单状态赋值为待付款;
					// 若为1,则将订单状态赋值为待发货
					String PAYSTATUS = (String) pd.get("PAYSTATUS");
					if ("1".equals(PAYSTATUS)) {
						List<PageData> orderInfos = orderService.selectOrderitemInfoByOrderId(pd);
						// 支付时间
						pd.put("PAY_TIME", ToolsUtil.getStringDate());
						// 修改订单支付状态以及支付时间
						orderService.updateOrder(pd);
						
						// 同时修改相对应商品的库存,通过订单id查询规格id,并修改库存
						// 通过购物车id查询车商品数量,以及相对应的库存
						for (PageData orderInfo : orderInfos) {
							
							int quantity = (int) orderInfo.get("QUANTITY");
							int proStock = (int) orderInfo.get("PRO_STOCK");
							int editProStock = proStock - quantity;
							
							pd.put("PRO_STOCK", editProStock);
							pd.put("STANDARD_ID", orderInfo.get("STANDARD_ID"));
							pd.put("ORDERITEM_ID", orderInfo.get("ORDERITEM_ID"));
							
							// 取出商品id
							String proId = (String) orderInfo.get("PRODUCT_ID");
							proIdList.add(proId);
							for (String pId : proIdList) {
								if (proId.equals(pId)) {
									if (!"".equals(proNumber.get(pId)) && proNumber.get(pId) != null) {
										Integer num = proNumber.get(pId);
										num += quantity;
										proNumber.put(pId, num);
									}
									proNumber.put(pId, quantity);
								}
							}
							
							// 修改库存
							cartInService.updStockByStandardId(pd);
							
							// 修改订单状态
							pd.put("ORDERSTATUS", "待发货");
							orderService.updateOrderStatus(pd);
						}
						
						// 如果使用优惠券,则改变db中的数量状态等
						if (!pd.get("COUPONUSER_ID").equals(null) && !pd.get("COUPONUSER_ID").equals("")) {
							pd.put("COUPON_STATE", "3");
							couponInService.editCoupon(pd);
							PageData couponId = couponInService.getCouponId(pd);
							pd.put("COUPON_ID", couponId.get("COUPON_ID"));
							PageData couponInfo = couponInService.findById(pd);
							// 已发送数量
							Integer sendCount = (Integer) couponInfo.get("SEND_COUNT");
							// 已核销数量
							Integer serdCount = (Integer) couponInfo.get("USED_COUNT");
							pd.put("SEND_COUNT", sendCount + 1);
							pd.put("USED_COUNT", serdCount + 1);
							couponInService.edit(pd);
						}
						
						for (String p : proIdList) {
							pd.put("PRODUCT_ID", p);
							
							PageData product = proInService.selectProByProId(pd);
							int stock = (int) product.get("STOCK");
							int salesNumber = (int) product.get("SALES_NUMBER");
							// logBefore(logger, (String)product.get("STOCK"));
							System.out.println("stock====" + stock + "salesNumber====" + salesNumber);
							int s = stock - proNumber.get(p);
							int sm = salesNumber + proNumber.get(p);
							
							pd.put("STOCK", s);
							pd.put("SALES_NUMBER", sm);
							
							productInService.updProduct(pd);
							
						}
						
						result = "01";
					} else {
						
						result = "02";
					}
					// logBefore(logger, pd.toString());
					
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
		
	}
*/
	/**
	 * 订单详情
	 * 
	 * @author zhanglingbing
	 * @date 2018年2月1日
	 * @return
	 */
	@RequestMapping(value = "/orderinfo")
	@ResponseBody
	public Object orderInfo() {
		logBefore(logger, "订单详情");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		logBefore(logger, pd.toString());
		try {
			if (Tools.checkKey("ORDERINFO", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("orderInfo", pd)) { // 检查参数
					/*
					 * Map<String,Object> map1 = new HashMap<String,Object>();
					 * //获取订单id String orderId = (String) pd.get("ORDER_ID");
					 * //通过订单id查询订单信息 PageData orderInfo =
					 * orderService.selectOrderInfoByOrderId(pd);
					 * map1.put("orderInfo", orderInfo);
					 * 
					 * //通过订单id查询收货信息 //获取地址id pd.put("ADDRESS_ID",
					 * orderInfo.get("ADDRESS_ID")); PageData adrInfo =
					 * orderService.selectAdrInfoByAdrId(pd);
					 * map1.put("addressInfo", adrInfo);
					 */
					// 查询订单中的商品信息(购物车)，获取商品规格
					// List<PageData> proInfo =
					// cartInService.selectCartListInfoByOrderId(pd);
					List<PageData> ordInfo = orderService.selectOrderitemInfoByOrderId(pd);
					// map1.put("proInfo", proInfo);
					// 返回01为结算至确认订单也查询成功
					map.put("pd", ordInfo);
					result = "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * 获得用户名下所有相关订单列表接口
	 * 
	 * @author zhanglingbing
	 * @date 2018年2月2日
	 * @return
	 */
	@RequestMapping(value = "/orderalllist")
	@ResponseBody
	public Object getAllOrderList() {
		logBefore(logger, "获得用户名下所有订单列表接口");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try {
			if (Tools.checkKey("ALLORDERLIST", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("getAllOrderList", pd)) { // 检查参数
					// 查询相关的订单列表
					List<PageData> allOrderList = orderService.getAllOrderList(pd);
					/*
					 * for (PageData p : allOrderList) {
					 * ToolsUtil.putImgstoArray(p, "PRODETAILSIMG"); }
					 */
					// 判断列表是否有数据
					if (allOrderList.size() != 0) {

						Map<Integer, Object[]> order = new HashMap<>();
						Set<String> name = new HashSet<>();
						List<String> nameNum = new ArrayList<>();

						// 获取购物车列表时将所有的选择状态置为0(不勾选状态)
						for (PageData orderInfo : allOrderList) {
							String shopName1 = (String) orderInfo.get("ORDERNUMBER");
							name.add(shopName1);
							nameNum.add(shopName1);

						}

						if (name.size() != 0) {
							Integer b = 0;// bname
							for (String n : name) {
								Map<String, String> bName = new HashMap<>();
								Map<String, PageData[]> cartIn = new HashMap<>();
								int a = 0;// pArr长度

								bName.put("orderNumber", n);
								// logBefore(logger, n);
								for (String nn : nameNum) {
									// logBefore(logger, nn);
									if (nn.equals(n)) {
										a++;
									}

								}
								PageData[] pArr = new PageData[a];
								a = 0;
								for (PageData cartInfo : allOrderList) {
									String shopName = (String) cartInfo.get("ORDERNUMBER");
									if (shopName.equals(n)) {
										String orderId = (String) cartInfo.get("ORDER_ID");
										bName.put("orderId", orderId);

										pArr[a] = cartInfo;
										a++;
									}

								}
								cartIn.put("orderInfo", pArr);
								Object[] cartInfoList = { bName, cartIn };
								order.put(b, cartInfoList);
								b++;
							}

						}

						map.put("pd", order);
					}
					result = (0 == allOrderList.size()) ? "02" : "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * 修改订单状态
	 * 
	 * @author zhanglingbing
	 * @date 2018年2月2日
	 * @return
	 */
	@RequestMapping(value = "/upordsta")
	@ResponseBody
	public Object updateOrderStatus() {
		logBefore(logger, "修改订单状态");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try {
			if (Tools.checkKey("UPORDSTA", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("updateOrderStatus", pd)) { // 检查参数

					List<PageData> orderItemList = orderService.selectOrderitemInfoByOrderId(pd);

					for (PageData orderInfo : orderItemList) {

						String orderStatus = (String) orderInfo.get("ORDERSTATUS");
						if ("待付款".equals(orderStatus)) {
							result = "06";
						} else {
							pd.put("ORDERSTATUS", pd.get("ORDERSTATUS"));
							pd.put("ORDERITEM_ID", orderInfo.get("ORDERITEM_ID"));
							orderService.updateOrderStatus(pd);
						}
					}
					result = "01";

					// 查询订单详情
					// PageData orderInfo =
					// orderService.selectOrderInfoByOrderId(pd);
					List<PageData> orderItems = orderService.getOrderItemById(pd);
					for (PageData p : orderItems) {
						p.put("BUSINESS_ID", pd.get("BUSINESS_ID"));
						p.put("ORDERSTATUS", pd.get("ORDERSTATUS"));
						orderService.updateOrderStatus(p);
					}
					result = "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * 删除订单
	 * 
	 * @author zhanglingbing
	 * @date 2018年2月2日
	 * @return
	 */
	@RequestMapping(value = "/delord")
	@ResponseBody
	public Object delorder() {
		logBefore(logger, "获得用户名下所有订单列表接口");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try {
			if (Tools.checkKey("DELORDER", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("delorder", pd)) { // 检查参数

					List<PageData> orderItemList = orderService.selectOrderitemInfoByOrderId(pd);
					int a = 0;
					for (PageData o : orderItemList) {
						pd.put("ORDERITEM_ID", o.get("ORDERITEM_ID"));

						orderService.delorderitem(pd);

						a++;
					}

					// orderService.delorder(pd);
					result = (a == orderItemList.size()) ? "01" : "02";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * 根据商家id查询订单列表
	 * 
	 * @Description
	 * @Author zhaozhenhua
	 * @date 2018年2月3日
	 * @param pd
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getorderlistbusi")
	@ResponseBody
	public Object getOrderListById() {
		logBefore(logger, "根据商家id查询订单列表");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try {
			if (Tools.checkKey("LISTORDERBUSI", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("getOrderNumAndMoney", pd)) { // 检查参数
					List<PageData> allOrderList = orderService.getOrderListById(pd);
					// 判断列表是否有数据
					if (allOrderList.size() != 0) {
						map.put("pd", allOrderList);
					}
					result = (0 == allOrderList.size()) ? "02" : "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * 根据订单id获取后台订单信息
	 * 
	 * @Description
	 * @Author zhaozhenhua
	 * @date 2018年2月22日
	 * @param pd
	 * @return
	 * @throws Exception
	 *             
	 */
	@RequestMapping(value = "/getorderinfobusi")
	@ResponseBody
	public Object getOrderInfoBusi() {
		logBefore(logger, "根据订单id获取后台订单信息");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try {
			if (Tools.checkKey("BACKENDORDERITEM", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("getOrderItemById", pd)) { // 检查参数
					List<PageData> orderItem = orderService.getOrderItemById(pd);
					if(orderItem!=null&&orderItem.size()!=0){
						PageData orderInfo = orderService.getOrderDetInfo(pd);
						if(orderInfo!=null){
							if(orderInfo.get("PAYSTATUS").equals("0")){
								orderInfo.put("PAYSTATUS", "未支付");
							}if(orderInfo.get("PAYSTATUS").equals("1")){
								orderInfo.put("PAYSTATUS", "已支付");
							}
							//判断列表是否有数据
							if (orderItem.size() != 0) {
								map.put("orderItems", orderItem);
								map.put("pd", orderInfo);
							}
							result = (0 == orderInfo.size()) ?  "02" :  "01";
						}
					}else{
						result = "02";
					}
				}else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * 后台获取物流管理订单信息
	 * 
	 * @Description
	 * @Author zhaozhenhua
	 * @date 2018年2月22日
	 * @param pd
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getlogisticsorders")
	@ResponseBody
	public Object getLogisticsOrders() {
		logBefore(logger, "后台获取物流管理订单信息");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(Tools.checkKey("LOGISTICSORDERS", pd.getString("FKEY"))){	//检验请求key值是否合法
				if(AppUtil.checkParam("getCouponListById", pd)){	//检查参数
					List<PageData> logisticsOrders = orderService.getLogisticsOrders(pd);
					for (PageData p : logisticsOrders) {
						BigDecimal totalprice = new BigDecimal(0);
						List<PageData> orderItems = orderService.getOrderItemById(p);
						for (PageData poi : orderItems) {
							BigDecimal big1 = new BigDecimal(poi.get("TOTAL_PRICE").toString());
							// 计算订单中不同商品的总价
							totalprice = totalprice.add(big1);
						}
						p.put("totalprice", totalprice);
						p.put("orderItems", orderItems);
					}
					// 判断列表是否有数据
					if (logisticsOrders.size() != 0) {
						map.put("list", logisticsOrders);
					}
					result = (0 == logisticsOrders.size()) ? "02" : "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * 后台获取订单数量和订单金额
	 * 
	 * @Description
	 * @Author zhaozhenhua
	 * @date 2018年2月24日
	 * @param pd
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getordernumandmoney")
	@ResponseBody
	public Object getOrderNumAndMoney() {
		logBefore(logger, "后台获取订单数量和订单金额");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try {
			if (Tools.checkKey("GETORDERNUMANDMONEY", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("getCouponListById", pd)) { // 检查参数
					// 获取所有订单总数和交易总额
					PageData p1 = orderService.getOrderNumberById(pd);
					PageData m1 = orderService.getOrderMoneyById(pd);
					map.put("all_order_num", p1.get("ORDERNUM"));
					if (m1 != null) {
						map.put("all_order_money", m1.get("ORDERMONEY"));
					} else {
						map.put("all_order_money", 0.00);
					}
					// 获取待发货订单总数
					pd.put("ORDERSTATUS", "待发货");
					PageData p2 = orderService.getOrderNumberById(pd);
					map.put("noDelivery_order_num", p2.get("ORDERNUM"));
					// 获取待付款订单总数
					pd.put("ORDERSTATUS", "待付款");
					PageData p3 = orderService.getOrderNumberById(pd);
					PageData m3 = orderService.getOrderMoneyById(pd);
					map.put("toBePaid_order_num", p3.get("ORDERNUM"));
					if (m3 != null) {
						map.put("toBePaid_order_money", m3.get("ORDERMONEY"));
					} else {
						map.put("toBePaid_order_money", 0.00);
					}
					// 获取已完成订单总数和已付金额
					pd.put("ORDERSTATUS", "已完成");
					PageData p4 = orderService.getOrderNumberById(pd);
					PageData m4 = orderService.getOrderMoneyById(pd);
					map.put("done_order_num", p4.get("ORDERNUM"));
					if (m4 != null) {
						map.put("done_order_money", m4.get("ORDERMONEY"));
					} else {
						map.put("done_order_money", 0.00);
					}
					// 获取退款金额
					pd.put("ORDERSTATUS", "退款/售后");
					PageData m5 = orderService.getOrderMoneyById(pd);
					if (m5 != null) {
						map.put("refund_order_money", m5.get("ORDERMONEY"));
					} else {
						map.put("refund_order_money", 0.00);
					}
					// 获取未完成订单总数
					map.put("noDone_order_num", p1.getLong("ORDERNUM") - p4.getLong("ORDERNUM"));
					result = "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}
	

}
